package cn.dlc.com.config;

import cn.dlc.com.filter.JwtLoginFilter;
import cn.dlc.com.filter.JwtVerifyFilter;
import cn.dlc.com.service.SysUserService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author deng
 * @date 2021/6/25 10:25
 **/
@Configuration
@EnableWebSecurity
@MapperScan("cn.dlc.com.mapper")
@EnableGlobalMethodSecurity(securedEnabled=true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SysUserService userService;

    @Autowired
    private RsaPropertiesConfig config;

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    // 配置springSecurity的相关信息
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // 释放静态资源，指定拦截规则，指定自定义认证页面，指定退出的配置，csrf配置
        httpSecurity
                .csrf()
                .disable()
                // 配置权限
                .authorizeRequests()
                // 其他资源必须拥有角色才能访问（这个anyrole指定的角色必须是以 “ROLE_” 开头的）
                .antMatchers("/product").hasAnyRole("USER", "ADMIN")
                // 这两个表示需要权限验证
                .anyRequest()
                .authenticated()

                .and()
                .addFilter(new JwtLoginFilter(super.authenticationManager(), config))
                .addFilter(new JwtVerifyFilter(super.authenticationManager(), config))
                // 禁用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }

    // 这样可以放行静态文件
    public void configure(WebSecurity web) throws Exception{

    }
}
